#!/bin/bash

set -e
set -u

. "$(dirname $0)/utils.sh"

APT_MIRROR_URL="http://deb.tails.boum.org/"
DEFAULT_COMPONENTS="main contrib non-free"
BASE_BRANCHES="stable testing devel feature/jessie"

output_apt_binary_source() {
	local suite="$1"
	local components="${2:-$DEFAULT_COMPONENTS}"

	echo "deb $APT_MIRROR_URL $suite $components"
}

output_overlay_apt_binary_sources() {
	for suite in $(ls config/APT_overlays.d) ; do
		output_apt_binary_source "$suite"
	done
}

on_base_branch() {
	local current_branch=$(current_branch)

	for base_branch in $BASE_BRANCHES ; do
		if [ "$current_branch" = "$base_branch" ] ; then
			return 0
		fi
	done

	return 1
}

### Sanity checks

[ -d config/APT_overlays.d ] || fatal 'config/APT_overlays.d/ does not exist'
[ -e config/base_branch  ]   || fatal 'config/base_branch does not exist'

[ "$(cat config/base_branch | wc -l)" -eq 1 ] \
    || fatal 'config/base_branch must contain exactly one line'

if on_base_branch && ! [ "$(base_branch)" = "$(current_branch)" ] ; then
	echo "base_branch: $(base_branch)" >&2
	echo "current_branch: $(current_branch)" >&2
	fatal "In a base branch, config/base_branch must match the current branch."
fi

### Main

if version_was_released "$(version_in_changelog)"; then
	if [ -n "$(ls config/APT_overlays.d)" ]; then
		fatal 'config/APT_overlays.d/ must be empty while releasing'
	fi
	output_apt_binary_source "$(branch_name_to_suite "$(version_in_changelog)")"
else
	output_apt_binary_source "$(branch_name_to_suite "$(base_branch)")"
	output_overlay_apt_binary_sources
fi

